package com.example.controller.user;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.pojo.entity.User;
import com.example.pojo.entity.UserProfile;
import com.example.result.Result;
import com.example.service.IUserProfileService;
import com.example.service.IUserService;
import com.example.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.http.HttpRequest;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zjw
 * @since 2024-07-16
 */
@RestController
@RequestMapping("/user-profile")
public class UserProfileController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IUserProfileService userProfileService;
    //修改用户信息
    @PutMapping("/modify")
    public Result handleModifyProfile(@RequestBody UserProfile userProfile) {
        try {
            //先根据id查询到数据

            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            User user = new User();
            BeanUtils.copyProperties(userProfile, user);
            wrapper.eq("id", userProfile.getId());
            userService.update(user, wrapper);
            UpdateWrapper<UserProfile> wrapper1 = new UpdateWrapper<>();
            wrapper1.eq("id", userProfile.getId());
            UserProfile userProfile1=new UserProfile();
            BeanUtils.copyProperties(userProfile,userProfile1);
            wrapper.eq("id", userProfile.getId());
            userProfileService.update(userProfile1, wrapper1);
            return Result.success();
        } catch (Exception e) {
            return Result.error();
        }

    }
   @GetMapping("/info")
    public Result getUserProfile(HttpServletRequest httpRequest) {

       Cookie[] cookies = httpRequest.getCookies();
       String token = null;
       for (Cookie cookie : cookies) {
           if (cookie.getName().equals("token")) {
                token=cookie.getValue();
           }
       }
       Claims claims = JwtUtil.parseJWT("itheima", token);
      Integer id = claims.get("userId", Integer.class);
       UserProfile user = userProfileService.getById(id);
       return Result.success(user);

   }
}
